package com.zuijin.vue2blog.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * --------------------------------------------
 * ClassName:    CorsConfig
 * CreateBy:     IntelliJ IDEA
 * Author:       醉瑾
 * Date:         2022-04-17
 * Description :
 * --------------------------------------------
 */
@Configuration
public class CorsConfig {
    private CorsConfiguration configuration() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedHeader(CorsConfiguration.ALL); // 添加要允许的实际请求标头。
        corsConfiguration.addAllowedMethod(CorsConfiguration.ALL); // 允许任何方法（post、get等）
        // corsConfiguration.addAllowedOrigin("http://localhost:8090/");
        corsConfiguration.addAllowedOriginPattern(CorsConfiguration.ALL); // 允许任何域名使用
        //corsConfiguration.setAllowedOriginPatterns(Collections.singletonList(CorsConfiguration.ALL));
        corsConfiguration.setAllowCredentials(true); // 此处设置为 true，则 addAllowedOrigin不能使用通配符
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration()); // 对接口配置跨域设置
        return new CorsFilter(source);
    }
}
